package com.example.demos.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demos.common.JwtUtils;
import com.example.demos.common.Md5Utils;
import com.example.demos.common.PassToken;
import com.example.demos.model.AdminUser;
import com.example.demos.model.User;
import com.example.demos.model.UserToken;
import com.example.demos.service.AdminUserService;
import com.example.demos.service.UserTokenService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class AdminUserController {

    @Resource
    private AdminUserService adminUserService;
    @Resource
    private UserTokenService userTokenService;


     @RequestMapping("/admin/userlist")
     @ResponseBody
    public List<Object> queryUserList(){
         List<Object> adminUserList= adminUserService.getList();
         return adminUserList;
    }




    /**
     * 用户登录：获取账号密码并登录，如果不对就报错，对了就返回用户的登录信息
     * 同时生成jwt返回给用户
     *
     * @return
     */
    @PassToken
    @ResponseBody
    @GetMapping(value = "/admin/login")
    public JSONObject login(String username,String password) throws Exception{
        JSONObject jsonObject=new JSONObject();
        try{
            System.out.println();
            AdminUser adminUser =  adminUserService.getUser(username);
            if (adminUser==null){
                jsonObject.put("code",201);
                jsonObject.put("msg","用户不存在");
                return jsonObject;
            }
            password = Md5Utils.getMd5Code(password+adminUser.getSalt());
            boolean login = adminUserService.login(username,password);
            if (login==false){
                jsonObject.put("code",201);
                jsonObject.put("msg","密码错误");
                return jsonObject;
            }
            String jwtToken = JwtUtils.createToken(adminUser.getId(),adminUser.getUsername(),adminUser.getNickname());
            int userToken = userTokenService.addAdminUserToken(adminUser.getId(),jwtToken,1);
            System.out.println(userToken);
            if (userToken<1){
                jsonObject.put("code",201);
                jsonObject.put("msg","登录失败");
                return jsonObject;
            }
            jsonObject.put("token",jwtToken);
            jsonObject.put("code",200);
            jsonObject.put("msg","登录成功");
        }
        catch (Exception e)
        {
            throw new Exception();
        }
        return jsonObject;
    }

}
